package com.cskaoyan.order.mq.consumer;

import com.alibaba.fastjson.JSON;
import com.cskaoyan.mall.order.dto.CreateSeckillOrderRequest;
import com.cskaoyan.order.service.OrderPromoService;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.nio.charset.Charset;
import java.util.List;

/**
 * @Description:
 * @since: 2022-11-03 12:10
 * @author: lazy
 */

@Component
public class CreatePromoOrderConsumer {

    private DefaultMQPushConsumer consumer;

    @Autowired
    OrderPromoService orderPromoService;

    @PostConstruct
    public void init() {

        // 创建consumer
        consumer = new DefaultMQPushConsumer("create_promo_order_consumer");

        // 设置nameserver地址
        consumer.setNamesrvAddr("127.0.0.1:9876");

        // 设置消息监听器
        consumer.setMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
                // 获取消息
                MessageExt message = list.get(0);

                // 获取消息体数据
                byte[] body = message.getBody();
                String requestJson = new String(body, 0, body.length, Charset.forName("utf-8"));
                CreateSeckillOrderRequest createSeckillOrderRequest = JSON.parseObject(requestJson, CreateSeckillOrderRequest.class);


                try {
                    orderPromoService.createPromoOrder(createSeckillOrderRequest);
                } catch (Exception e) {
                    e.printStackTrace();
                    return ConsumeConcurrentlyStatus.RECONSUME_LATER;
                }

                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });

        // 订阅主题
        try {
            consumer.subscribe("create_promo_order", "*");

            consumer.start();
        } catch (MQClientException e) {
            e.printStackTrace();
        }

    }



}
